package org.example.utils;


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
public class PdfUtils {

    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, AcroFields.Item> formFields = fields.getFields();
        for (String key : data.keySet()) {
            if(formFields.containsKey(key)){
                String value = data.get(key);
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        Iterator<String> itemsKey = formFields.keySet().iterator();
        while(itemsKey.hasNext()){
            String itemKey = itemsKey.next();
            if(!keys.contains(itemKey)){
                fields.setField(itemKey, " ");
            }
        }
    }
    /**
     * @param templatePdfName
     *            模板pdf名称
     * @param generatePdfPath
     *            生成pdf路径
     * @param data
     *            数据
     */
    public static String generatePDF(String templatePdfName, String generatePdfPath, Map<String, String> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            byte[] bytes =generatePDF(templatePdfName,data);
            fos = new FileOutputStream(generatePdfPath);
            fos.write(bytes);
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * @param templatePdfName
     *            模板pdf名称
     * @param data
     *            数据
     */
    public static byte[] generatePDF(String templatePdfName,  Map<String, String> data) {
        ByteArrayOutputStream bos = null;
        try {
            InputStream istemplate =PdfUtils.class.getClassLoader().getResourceAsStream(templatePdfName);
            PdfReader reader = new PdfReader(istemplate);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            //BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            BaseFont bf = BaseFont.createFont(
                    "src/main/resources/fonts/simhei.ttf", // 黑体文件路径
                    BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED
            );
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            Set<String> strings = fields.getFields().keySet();
            for (String key : strings) {
                fields.setFieldProperty(key, "textsize", 19f, null);
                fields.setFieldProperty(key, "textfont", bf, null);
            }
            fillData(fields, data);
            /* 特殊字段增强样式 */
            if (fields.getFields().containsKey("reportCode")) {

            }
            /* 必须要调用这个，否则文档不会生成的  如果为false那么生成的PDF文件还能编辑，一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();
            return bos.toByteArray();
            // return bos;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void exportPDF(HttpServletResponse response, String fileName, byte[] pdfBytes) throws IOException {
//        if (StringUtils.isBlank(fileName)) {
//            //当前日期
//            fileName = DateUtils.format(new Date());
//        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
        ServletOutputStream out = response.getOutputStream();
        // 使用工具类直接将文件的字节复制到响应输出流中

        //FileCopyUtils.copy(new FileInputStream(new File("123456.pdf")), out);
        //out.write(pdfBytes);
        //out.write(pdfBytes);
        //通过输入流获取图片数据
//        InputStream inStream = conn.getInputStream();
//        byte[] buffer = new byte[1024];
//        int len;
//        baos = new ByteArrayOutputStream();
//        while ((len=inStream.read(buffer))!=-1){
//            baos.write(buffer,0,len);
//        }
//        response.addHeader("Content-Disposition", "attachment;filename=" + url);
//        response.addHeader("Content-Length", "" + baos.size());
//        response.setHeader("filename", url);
//        response.setContentType("application/octet-stream");
//        out = response.getOutputStream();
        out.write(pdfBytes);

        out.flush();
    }

    public static void main(String[] args) {
        Map<String, String> data = new HashMap<String, String>();
        //第一页内容
        data.put("reportCode", "11d1564510-24");
        data.put("reportAddress","上海市闵行区虹梅南路");
        data.put("homeCode","22-1");
        data.put("client","张有志");
        data.put("acceptanceType","毛坯");
        data.put("author","赵非凡");
        data.put("reportTime","2025-04-25");
        generatePDF("最新模板.pdf",
                "最新模板1.pdf", data );
    }
}